<template>
  <div class="false-positive-list">
    <!-- 筛选表单 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <DynamicForm
        ref="formRef"
        v-model="formData"
        :form-config="formConfig"
        :gutter="16"
        label-width="100px"
        type="search"
        @search="handleSearch"
        @reset="handleReset"
      />
    </el-card>

    <!-- 操作工具栏 -->
    <!-- <el-card class="toolbar-card" :body-style="{ padding: '15px' }">
      <div class="toolbar-content">
        <div class="toolbar-left">
          <el-button type="default" icon="Refresh" @click="handleRefresh">
            刷新
          </el-button>
          <el-button type="primary" icon="CirclePlus" @click="handleSubmit">
            提交误报申请
          </el-button>
          <el-button type="primary" icon="PieChart" @click="handleAnalysis">
            统计分析
          </el-button>
        </div>
        <div class="toolbar-right" v-if="selectedRows.length > 0">
          <span class="selected-count"
            >已选择 {{ selectedRows.length }} 项</span
          >
          <el-button type="success" icon="Check" @click="handleBatchConfirm">
            批量确认
          </el-button>
          <el-button type="warning" icon="Close" @click="handleBatchIgnore">
            批量忽略
          </el-button>
          <el-button type="primary" icon="Plus" @click="handleBatchWhitelist">
            加白名单
          </el-button>
        </div>
      </div>
    </el-card> -->

    <!-- 数据表格 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <DynamicTable
        ref="tableRef"
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        :selection-type="'multiple'"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <template #table-top>
          <div class="table-toolbar">
            <div class="toolbar-left">
              <el-button type="primary" @click="handleSubmit">
                提交误报申请
              </el-button>
              <el-button type="default" @click="handleRefresh">
                刷新
              </el-button>
            </div>
            <div class="toolbar-right">
              <span class="selected-count"
                >已选择 {{ selectedRows.length }} 项</span
              >
              <el-button
                :disabled="selectedRows.length === 0"
                type="success"
                @click="handleBatchConfirm"
              >
                批量确认
              </el-button>
              <el-button
                :disabled="selectedRows.length === 0"
                type="warning"
                @click="handleBatchIgnore"
              >
                批量忽略
              </el-button>
              <el-button
                :disabled="selectedRows.length === 0"
                type="primary"
                @click="handleBatchWhitelist"
              >
                加白名单
              </el-button>
            </div>
          </div>
        </template>
        <template #status="{ row }">
          <el-tag :type="getStatusTagType(row.status_type)" size="small">
            {{ row.status_label || getStatusText(row.status_type) }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-button size="small" @click="handleViewDetail(row)">
            详情
          </el-button>
          <el-button
            v-if="row.status_type === 'pending'"
            size="small"
            class="text-success"
            @click="handleConfirm(row)"
          >
            确认
          </el-button>
          <el-button
            v-if="row.status_type === 'pending'"
            size="small"
            class="text-danger"
            @click="handleReject(row)"
          >
            拒绝
          </el-button>
          <el-button
            v-if="row.status_type === 'pending'"
            size="small"
            class="text-warning"
            @click="handleIgnore(row)"
          >
            忽略
          </el-button>
          <el-button
            v-if="row.status_type === 'pending'"
            size="small"
            @click="handleAddWhitelist(row)"
          >
            加白
          </el-button>
          <el-button
            v-if="row.status_type === 'cancelled'"
            size="small"
            class="text-primary"
            @click="handleRecover(row)"
          >
            恢复
          </el-button>
        </template>
      </DynamicTable>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import { getFalsePositiveListEnhanced } from "../../../servers";

// 定义属性和事件
const props = defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits([
  "refresh",
  "submit",
  "analysis",
  "view-detail",
  "confirm",
  "reject",
  "ignore",
  "recover",
  "add-whitelist",
  "batch-confirm",
  "batch-ignore",
  "batch-whitelist",
]);

const formRef = ref<DynamicFormInstance>();
const tableRef = ref<DynamicTableInstance>();

// 表格数据
const tableData = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 表单数据
const formData = reactive({
  asset_ip: "",
  dimension_code: "",
  status: "all",
  review_status: "",
  marked_by: "",
  reviewed_by: "",
  start_time: "",
  end_time: "",
  keyword: "",
  sort_field: "marked_at",
  sort_order: "desc",
});

// 表单配置
const formConfig: FormItemConfig[] = [
  {
    key: "asset_ip",
    name: "资产IP",
    type: "input",
    labelWidth: "60px",
    placeholder: "输入资产IP（支持模糊搜索）",
    params: {
      clearable: true,
    },
    col: { span: 5 },
  },
  {
    key: "dimension_code",
    name: "维度代码",
    type: "input",
    placeholder: "输入维度代码",
    params: {
      clearable: true,
    },
    col: { span: 5 },
  },
  {
    key: "status",
    name: "状态",
    type: "select",
    placeholder: "选择状态",
    params: {
      clearable: false,
    },
    options: [
      { label: "全部", value: "all" },
      { label: "已标记", value: "active" },
      { label: "已取消", value: "inactive" },
    ],
    col: { span: 4 },
  },
  {
    key: "review_status",
    name: "审核状态",
    type: "select",
    placeholder: "选择审核状态",
    params: {
      clearable: true,
    },
    options: [
      { label: "全部", value: "" },
      { label: "已审核", value: "reviewed" },
      { label: "待审核", value: "pending" },
    ],
    col: { span: 4 },
  },
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "搜索原因和证据",
    params: {
      clearable: true,
    },
    col: { span: 6 },
  },
];

// 表格列配置
const columns: TableColumn[] = [
  {
    label: "序号",
    prop: "serialNumber",
    width: 80,
    align: "center",
    formatter: (row: any, column: any, cellValue: any, index: number) => {
      return String(
        (pagination.currentPage - 1) * pagination.pageSize + index + 1
      );
    },
  },
  {
    label: "资产IP",
    prop: "asset_ip",
    minWidth: 120,
  },
  {
    label: "资产名称",
    prop: "asset_name",
    minWidth: 150,
    showOverflowTooltip: true,
  },
  {
    label: "维度代码",
    prop: "dimension_code",
    minWidth: 150,
  },
  {
    label: "维度名称",
    prop: "dimension_name",
    minWidth: 150,
    showOverflowTooltip: true,
  },
  {
    label: "误报原因",
    prop: "false_positive_reason",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "状态",
    prop: "status_type",
    minWidth: 100,
    align: "center",
    slot: "status",
  },
  {
    label: "标记人",
    prop: "marked_by",
    minWidth: 100,
  },
  {
    label: "标记时间",
    prop: "marked_at",
    minWidth: 160,
  },
  {
    label: "审核人",
    prop: "reviewed_by",
    minWidth: 100,
    formatter: (row: any) => row.reviewed_by || "-",
  },
  {
    label: "审核时间",
    prop: "reviewed_at",
    minWidth: 160,
    formatter: (row: any) => row.reviewed_at || "-",
  },
  {
    label: "操作",
    prop: "action",
    minWidth: 220,
    fixed: "right",
    slot: "action",
  },
];

// 获取状态文本
const getStatusText = (statusType: string) => {
  const statusMap: Record<string, string> = {
    pending: "待审核",
    reviewed: "已审核",
    cancelled: "已取消",
  };
  return statusMap[statusType] || statusType;
};

// 获取状态标签类型
const getStatusTagType = (
  statusType: string
): "success" | "info" | "warning" | "danger" => {
  const typeMap: Record<string, "success" | "info" | "warning" | "danger"> = {
    pending: "info",
    reviewed: "success",
    cancelled: "warning",
  };
  return typeMap[statusType] || "info";
};

// 获取列表数据
const fetchList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
      sort_field: formData.sort_field,
      sort_order: formData.sort_order,
    };

    // 添加筛选条件
    if (formData.asset_ip) params.asset_ip = formData.asset_ip;
    if (formData.dimension_code)
      params.dimension_code = formData.dimension_code;
    if (formData.status && formData.status !== "all")
      params.status = formData.status;
    if (formData.review_status) params.review_status = formData.review_status;
    if (formData.marked_by) params.marked_by = formData.marked_by;
    if (formData.reviewed_by) params.reviewed_by = formData.reviewed_by;
    if (formData.start_time) params.start_time = formData.start_time;
    if (formData.end_time) params.end_time = formData.end_time;
    if (formData.keyword) params.keyword = formData.keyword;

    const { data } = await getFalsePositiveListEnhanced(params);

    tableData.value = data.items || [];
    pagination.total = data.total || 0;
  } catch (error: any) {
    console.error("获取列表失败:", error);
    ElMessage.error(error.message || "获取列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchList();
  emit("refresh");
};

// 重置
const handleReset = () => {
  formData.asset_ip = "";
  formData.dimension_code = "";
  formData.status = "all";
  formData.review_status = "";
  formData.marked_by = "";
  formData.reviewed_by = "";
  formData.start_time = "";
  formData.end_time = "";
  formData.keyword = "";
  formData.sort_field = "marked_at";
  formData.sort_order = "desc";
  pagination.currentPage = 1;
  fetchList();
  emit("refresh");
};

// 刷新
const handleRefresh = () => {
  fetchList();
  emit("refresh");
};

// 分页变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList();
};

const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchList();
};

// 选择变化
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

// 提交误报申请
const handleSubmit = () => {
  emit("submit");
};

// 统计分析
const handleAnalysis = () => {
  emit("analysis");
};

// 查看详情
const handleViewDetail = (row: any) => {
  emit("view-detail", row);
};

// 确认
const handleConfirm = (row: any) => {
  emit("confirm", row);
};

// 拒绝
const handleReject = (row: any) => {
  emit("reject", row);
};

// 忽略
const handleIgnore = (row: any) => {
  emit("ignore", row);
};

// 恢复
const handleRecover = (row: any) => {
  emit("recover", row);
};

// 加白名单
const handleAddWhitelist = (row: any) => {
  emit("add-whitelist", row);
};

// 批量确认
const handleBatchConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }
  emit("batch-confirm", selectedRows.value);
};

// 批量忽略
const handleBatchIgnore = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }
  emit("batch-ignore", selectedRows.value);
};

// 批量加白名单
const handleBatchWhitelist = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要操作的记录");
    return;
  }
  emit("batch-whitelist", selectedRows.value);
};

// 暴露方法给父组件
defineExpose({
  fetchList,
  clearSelection: () => {
    tableRef.value?.clearSelection();
  },
  getSelectionRows: () => {
    return selectedRows.value;
  },
});

// 组件挂载时加载数据
onMounted(() => {
  fetchList();
});
</script>

<style scoped lang="scss">
.false-positive-list {
  .filter-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .toolbar-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .toolbar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
  }

  .toolbar-left {
    display: flex;
    gap: 10px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .selected-count {
    color: #666;
    font-size: 14px;
    margin-right: 10px;
  }

  .table-card {
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .text-success {
    color: #52c41a !important;
  }

  .text-warning {
    color: #faad14 !important;
  }

  .text-primary {
    color: #1890ff !important;
  }

  .text-danger {
    color: #f5222d !important;
  }

  .table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #f0f0f0;
  }

  .toolbar-left {
    display: flex;
    gap: 10px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .selected-count {
    color: #666;
    font-size: 14px;
    margin-right: 10px;
  }
}

::v-deep .el-form-item {
  margin-bottom: 10px;
}
</style>
